package com.huatai.bpmn.commom.util;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huatai.bpmn.commom.constant.BaseConstant;
import com.huatai.common.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author :yxy
 * @date : 2023/7/10
 * 用于查询时，由于动态表单的列特殊，需要做处理才可使用
 */
@Component
@Slf4j
public class BaseCommService<T> {
	/**
	 * 构造默认的查询条件
	 *
	 * @param map
	 * @return
	 */
	public QueryWrapper<T> buildQW(Map<String, Object> map) {
		QueryWrapper<T> qw = new QueryWrapper<T>();
		if (ObjectUtil.isEmpty(map)) {
			return qw;
		}
		//先设置排序
		String order = map.getOrDefault(BaseConstant.SerachKeyPrfix.ORDER_ORDER_BY, "").toString();
		if (StrUtil.isNotBlank(order) && !order.equalsIgnoreCase(":")) {
			//orderby 格式为:字段1,字段2:ASC或DSC
			String[] orders = StrUtil.split(order, ':', true, true).toArray(new String[0]);
			if (orders.length > 0) {
				String orderType = orders.length == 2 ? orders[1].toUpperCase() : "ASC";
				String[] orderColumns = StrUtil.split(orders[0], ',', true, true).toArray(new String[0]);
				qw.orderBy(true, orderType.equals("ASC"), Arrays.asList(orderColumns));
			}
		}
		for (Map.Entry<String, Object> entry : map.entrySet()) {
			String queryKey = entry.getKey();
			String columnName = "";
			String columnValue = ObjectUtil.isEmpty(entry.getValue()) ? "" : entry.getValue().toString();
			if (queryKey.contains("pg") || ObjectUtil.isEmpty(columnValue)) {  //过滤分页的部分参数
				continue;
			}
			// 跳出不满足条件的参数
			if (!queryKey.startsWith(BaseConstant.SerachKeyPrfix.SEARCH)
				|| StrUtil.isBlank(columnValue)
				|| columnValue.equals("[]")) {
				continue;
			}
			//like
			if (StrUtil.startWith(queryKey, BaseConstant.SerachKeyPrfix.SEARCH_LIKE)) {
				columnName = StrUtil.removePrefix(queryKey, BaseConstant.SerachKeyPrfix.SEARCH_LIKE);
				qw.like(columnName, columnValue);
				continue;
			}
			//notlike
			if (StrUtil.startWith(queryKey, BaseConstant.SerachKeyPrfix.SEARCH_NOTLIKE)) {
				columnName = StrUtil.removePrefix(queryKey, BaseConstant.SerachKeyPrfix.SEARCH_NOTLIKE);
				qw.notLike(columnName, columnValue);
				continue;
			}
			//equal
			if (StrUtil.startWith(queryKey, BaseConstant.SerachKeyPrfix.SEARCH_EQUAL)) {
				columnName = StrUtil.removePrefix(queryKey, BaseConstant.SerachKeyPrfix.SEARCH_EQUAL);
				qw.eq(columnName, columnValue.equals("true") || columnValue.equals("false") ? Boolean.valueOf(columnValue) : columnValue);
				continue;
			}
			//notequal
			if (StrUtil.startWith(queryKey, BaseConstant.SerachKeyPrfix.SEARCH_NOTEQUAL)) {
				columnName = StrUtil.removePrefix(queryKey, BaseConstant.SerachKeyPrfix.SEARCH_NOTEQUAL);
				qw.ne(columnName, columnValue);
				continue;
			}
			//ge
			if (StrUtil.startWith(queryKey, BaseConstant.SerachKeyPrfix.SEARCH_GE)) {
				columnName = StrUtil.removePrefix(queryKey, BaseConstant.SerachKeyPrfix.SEARCH_GE);
				qw.ge(columnName, columnValue);
				continue;
			}
			//le
			if (StrUtil.startWith(queryKey, BaseConstant.SerachKeyPrfix.SEARCH_LE)) {
				columnName = StrUtil.removePrefix(queryKey, BaseConstant.SerachKeyPrfix.SEARCH_LE);
				qw.le(columnName, columnValue);
				continue;
			}
			//in
			if (StrUtil.startWith(queryKey, BaseConstant.SerachKeyPrfix.SEARCH_IN)) {
				columnName = StrUtil.removePrefix(queryKey, BaseConstant.SerachKeyPrfix.SEARCH_IN);
				if (!JSONObject.isValidArray(columnValue)) {
					log.error("关键词[{}]的值格式错误，值格式为数组类型:[值1,值2...]，但实际接收到的值为:{}，", queryKey, columnValue);
				}
				List<Object> columnValues = JSONObject.parseArray(columnValue, Object.class);
				if (StringUtil.isEmpty(columnValues)) {
					continue;
				}
				qw.in(columnName, columnValues);
			}
			//between
			if (StrUtil.startWith(queryKey, BaseConstant.SerachKeyPrfix.SEARCH_BETWEEN)) {
				columnName = StrUtil.removePrefix(queryKey, BaseConstant.SerachKeyPrfix.SEARCH_BETWEEN);
				if (!JSONObject.isValidArray(columnValue)) {
					log.error("关键词[{}]的值格式错误，值格式为：最小值,最大值，或数组类型:[最小值,最大值]，但实际接收到的值为:{}，", queryKey, columnValue);
				}
				List<Object> columnValues = JSONObject.parseArray(columnValue, Object.class);
				if (StringUtil.isEmpty(columnValues)) {
					continue;
				}
				if (columnValues.size() != 2) {
					columnValues = Arrays.asList(StrUtil.split(columnValue, ',', true, true).toArray());
				}
				//结束日期加一天
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
				Date parse = null;
				try {
					parse = df.parse(columnValues.get(1).toString());
				} catch (ParseException e) {
					e.printStackTrace();
				}
				Calendar calendar = new GregorianCalendar();
				calendar.setTime(parse);
				calendar.add(calendar.DATE, 1); //把日期往后增加一天,整数  往后推,负数往前移动
				parse = calendar.getTime(); //这个时间就是日期往后推一天的结果
				String s = dateUtils.dateToStr(parse, DateThreadUtils.sdf_yyyy_mm_dd.get());
				qw.between(columnName, columnValues.get(0), s);
				continue;
			}
		}
		return qw;
	}


	/**
	 * 从map的key-value中生成Pageable对象
	 *
	 * @param index 当前索引页，其中1表示第一页
	 * @param size  每页大小
	 * @return
	 */
	public IPage buildPage(int index, int size) {
		index = index < 1 ? 1 : index;
		size = size < 1 ? 10 : size;
		return new Page(index, size);
	}
}
